package org.xuk.spring.ws.service;

import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;
import org.xuk.spring.ws.constants.WsConstants;
import org.xuk.spring.ws.model.AbstractMessage;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class WsMessageClient {
    private final SimpMessageSendingOperations simpMessageSendingOperations;

    public WsMessageClient(SimpMessageSendingOperations simpMessageSendingOperations) {
        this.simpMessageSendingOperations = simpMessageSendingOperations;
    }

    public void sendToUsers(List<String> userIds, final AbstractMessage message) {
        for (String userId : userIds) {
            String topic = message.getTopic();
            //在给用户发送消息时，得去掉/user前缀
            if (topic.startsWith(WsConstants.USER_DESTINATION_PREFIX)) {
                topic = topic.substring(WsConstants.USER_DESTINATION_PREFIX.length());
            }
            simpMessageSendingOperations.convertAndSendToUser(userId, topic,
                    message.getMessageData().getBody(),
                    getMessageHeaders(message.getMessageData().getHeaders()));
        }
    }

    public void boardCast(final AbstractMessage message) {
        simpMessageSendingOperations.send(message.getTopic(), toGenericMessage(message));
    }

    private GenericMessage<byte[]> toGenericMessage(final AbstractMessage message) {
        return new GenericMessage<>(message.getMessageData().getBody().getBytes(StandardCharsets.UTF_8),
                getMessageHeaders(message.getMessageData().getHeaders()));
    }

    private Map<String, Object> getMessageHeaders(Map<String, String> headers) {
        Map<String, Object> genericHeaders = new HashMap<>();
        genericHeaders.putAll(headers);
        return genericHeaders;
    }
}
